package com.scud.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.scud.model.system.dto.LoginDto;
import com.scud.model.system.pojo.Permission;
import com.scud.model.system.pojo.User;
import com.scud.system.mapper.PermissionMapper;
import com.scud.system.mapper.UserRoleMapper;
import com.scud.system.model.LoginUser;
import com.scud.system.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        //解析json字符串，判断认证方式
        LoginDto loginDto = JSONObject.parseObject(username, LoginDto.class);
        //根据认证方式获取不同bean，authType取值有password,code
        String authType = loginDto.getAuthType();
        AuthService authService = applicationContext.
                getBean(authType + "_auth",AuthService.class);
        //进行认证操作
        User user = authService.execute(loginDto);
        //获取用户权限信息
        List<String> permissionList=new ArrayList<>();
        List<Permission> list=permissionMapper.selectByUserId(user.getId());
        for (Permission permission : list) {
            if (permission.getValue()==null || permission.getValue().equals("")){
                continue;
            }
            permissionList.add(permission.getValue());
        }
        //返回UserDetails对象
        return new LoginUser(user,permissionList);
    }
}
